package leetcode.hot100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
public class _17_电话号码的字母组合 {
    // 在键盘上输入数字“23”可以产生的组合有["ad","ae","af","bd","be","bf","cd","ce","cf"]

    List<String> combinations;
    Map<Character, String> phoneMap;
    String digits;

    public List<String> letterCombinations(String digits) {
        combinations = new ArrayList<>();
        if (digits.length() == 0) {
            return combinations;
        }
        this.digits = digits;
        // 使用哈希表存储每个数字对应的所有可能的字母
        phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backtrack(0, new StringBuffer());
        return combinations;
    }

    public void backtrack(int index, StringBuffer combination) {
        if (index == digits.length()) {
            // 7.添加ad
            combinations.add(combination.toString());
            return;
        }
        // 1.先取出23中的2
        char digit = digits.charAt(index);
        // 2.得到数字2对应的字母
        String letters = phoneMap.get(digit);
        // 3.对应的字母数量
        int lettersCount = letters.length();
        // 排列组合
        for (int i = 0; i < lettersCount; i++) {
            // 4.添加a ---  6.添加d
            combination.append(letters.charAt(i));
            // 5.找到3
            backtrack(index + 1, combination);
            // 8.删除ad中的d
            combination.deleteCharAt(index);
        }
    }
}
